package com.atguigu.boot04.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author:朱思博
 * @date:2021/5/11-{17:21}
 *
 * 用Redis
 * 统计indexController中
 *  /login,/   /admin
 *  上述命令的访问次数
 */
@Component
public class RedisUrlCountInterceptor implements HandlerInterceptor {
    @Autowired
    StringRedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();

        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        // 每次访问uri都会计数加一
        ops.increment(uri);

        // 要注意这里的方法最后要返回true，因为该拦截器不起拦截作用，只是计数，所以无论如何要放行
        return true;
    }
}
